package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.seckill.SeckillStatus;
import com.qingcheng.service.seckill.SeckillOrdersService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/seckill/order")
public class SeckillOrderController {

    @Reference
    private SeckillOrdersService seckillOrdersService;

    /**
     * 秒杀下单
     * @param id 商品id
     * @param time 商品所在的时区
     * @return
     */
    @RequestMapping("/add")
    public Result add(Long id,String time){
        try {
            //获取用户名
            String username = SecurityContextHolder.getContext().getAuthentication().getName();

            //如果用户账号为匿名登录anonymousUser，则表示用户未登录
            if(username.equals("anonymousUser")){
                return new Result(403,"请先登录!");
            }

            //添加商品
            boolean bool = seckillOrdersService.add(id, time, username);
            if(bool){
                return new Result(0,"下单成功！");
            }else{
                return new Result(1,"下单失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(2,e.getMessage());
        }
    }

    /**
     * 查询抢单的状态
     * @return
     */
    @RequestMapping(value = "/query")
    public Result queryStatus(){

        //获取用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        //当前用户未登录
        if(username.equals("anonymousUser")){
            System.out.println("经过了未登录");
            return new Result(403,"请先登录");
        }

        try {
            //根据用户民查询用户登录状态
            SeckillStatus seckillStatus = seckillOrdersService.queryStatus(username);

            if(seckillStatus!=null){
                Result result = new Result(seckillStatus.getStatus(),"抢单状态");
                result.setOther(seckillStatus); //封装抢单信息
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(6,e.getMessage());
        }

        return new Result(404,"没有抢购信息");
    }
}
